package com.glorysoft.hlgdpda.ui.materialandtool.viewmodel

import androidx.core.text.isDigitsOnly
import androidx.databinding.ObservableArrayList
import com.glorysoft.hlgdpda.BR
import com.glorysoft.hlgdpda.R
import com.glorysoft.hlgdpda.base.BaseViewModel
import com.glorysoft.hlgdpda.entity.LotEntity
import com.glorysoft.hlgdpda.entity.ui.CallObserveBean
import com.glorysoft.hlgdpda.entity.ui.ToastMessageBean
import com.glorysoft.hlgdpda.model.TaskRepository
import com.google.gson.JsonObject
import me.tatarka.bindingcollectionadapter2.ItemBinding

/**
 * FileName: BatchBindCarrierViewModel
 * Author: XJH
 * Date: 2021/11/10 15:52
 * Description:
 * History:
 */
class BatchBindCarrierViewModel : BaseViewModel() {

    val lotList: List<String> = listOf("批次号", "工步名称", "载具ID")

    //batch 批次列表
    var batchItems = ObservableArrayList<LotEntity.LotInfoEntity>()
    private val batchRepository = TaskRepository()
    var batchItemsBinding =
        ItemBinding.of<LotEntity.LotInfoEntity>(BR.batchItem, R.layout.item_batch_bind_carrier)

    /**
     * 获取batch信息
     *
     */
    fun searchBatchInfo(batch: String) {
        val map = JsonObject()
        map.addProperty("BATCHID", batch)
        launchOnlyResult({
            val mLotInfo = batchRepository.getBatchInfo(map)
            batchItems.addAll(mLotInfo.LOTLIST)
            defUI.callObserve.value = CallObserveBean(210, batchItems.size)
        })
    }

    /**
     * 获取批次信息
     */
    fun searchLotInfo(lot: String) {
        val map = JsonObject()
        map.addProperty("ACTIONTYPE", "LOTINFOBYID")
        map.addProperty("LOTID", lot)
        launchOnlyResult({
            val lotInfo = batchRepository.getLotInfo(map)
            batchItems.add(lotInfo.LOT)
            defUI.callObserve.value = CallObserveBean(210, batchItems.size)
        })
    }

    fun checkData() {
        if (batchItems.isEmpty()) {
            defUI.toastEvent.value = ToastMessageBean("请先添加批次信息", false)
            return
        }

        batchItems.forEach {
            if (it.CARRIERID.isEmpty()) {
                defUI.toastEvent.value = ToastMessageBean("请先输入载具ID", false)
                return
            }
        }
        submit()
    }

    private fun submit() {
        val sb = StringBuilder()
        var lotID = ""
        var i = 0
        launchWithErrorAndComplete({
            batchItems.forEachIndexed { index, lotInfoEntity ->
                lotID = lotInfoEntity.LOTID
                i = index
                val map = JsonObject()
                map.addProperty("LOTID", lotInfoEntity.LOTID)
                map.addProperty("CARRIERID", lotInfoEntity.CARRIERID)
                batchRepository.carrierBindLot(map)
            }
        }, { sb.append("$lotID;") }, {
            if (i == batchItems.size - 1) {
                defUI.callObserve.value = CallObserveBean(200, sb.toString())
            }
        })


    }

}